package com.tct.worktimeboard.config;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tct.worktimeboard.entity.UserInfo;
import com.tct.worktimeboard.entity.Work;
import com.tct.worktimeboard.feishu.FeiShuUtil;
import com.tct.worktimeboard.feishu.MessageEntity;
import com.tct.worktimeboard.feishu.SendMessage;
import com.tct.worktimeboard.mapper.UserInfoMapper;
import com.tct.worktimeboard.mapper.WorkMapper;
import com.tct.worktimeboard.service.OAService;
import com.tct.worktimeboard.util.ListUtil;
import com.tct.worktimeboard.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Huhailong
 * @Description 定时任务类
 * @Date 2021/3/5.
 */
@Slf4j
@Configuration
@EnableScheduling
public class CronConfig {

    @Resource
    WorkMapper workMapper;
    @Resource
    UserInfoMapper userInfoMapper;
    @Autowired
    SendMessage sendMessage;
    @Autowired
    FeiShuUtil feiShuUtil;
    @Autowired
    OAService oaService;
    
    @Scheduled(cron = "0 0 17 * * ?")
    public void sendMessageByWorkTime(){
        log.info("执行定时任务，当前时间：{}",TimeUtil.getDateTime());
        log.info("send add work time message...");
        sendMessageToWriteWorkTime();
        log.info("send message successful!");
        log.info("send make work time message...");
        sendNotMakeMessage();
        log.info("send message successful!");
    }

    /**
     * 根据工时填报信息给没有填报工时的用户发送消息
     */
    public void sendMessageToWriteWorkTime(){
        log.info("进入发送消息方法：给填报人发送");
        QueryWrapper<Work> wrapper = new QueryWrapper<>();
        wrapper.lt("work_end_time", TimeUtil.getDate());
        wrapper.select("DISTINCT user_id");
        List<Work> works = workMapper.selectList(wrapper);  //获取工时结束日期小于今天的用户
        List<Integer> collect = works.stream().map(Work::getUserId).collect(Collectors.toList());
        List<Integer> collect1 = collect.stream().distinct().collect(Collectors.toList());
        List<Integer> notWorkTimeUserList = workMapper.getNotWorkTimeUserIds(); //获取除上述用户外没有填报工时记录的用户
        List<Integer> collect2 = notWorkTimeUserList.stream().distinct().collect(Collectors.toList());
        collect1.addAll(collect2);
        DataSourceContextHolder.setContextHolder("db2");
        List<UserInfo> userInfos = userInfoMapper.selectList(new QueryWrapper<UserInfo>().select("phone").in("id", collect1));
        DataSourceContextHolder.clear();
        List<String> userTels = userInfos.stream().map(UserInfo::getPhone).collect(Collectors.toList());
        //将查询到的用户手机号按照没个list50个手机号进行分割查询用户openid（因为飞书根据手机号查询用户的参数限制未最大50个）
        List<List<String>> lists = ListUtil.cutApart(50, userTels.stream().distinct().collect(Collectors.toList()));
        List<String> allReadSendUserList = new ArrayList<>();
        //循环根据手机号查询用户openid列表
        for(List<String> tels : lists){
            List<String> userInfoList = feiShuUtil.getUserInfoList(tels);
            allReadSendUserList.addAll(userInfoList);
        }
        log.info("要发送的opendid:{}",allReadSendUserList);
        List<List<String>> sendOpens = ListUtil.cutApart(200, allReadSendUserList);
        log.info("分割后的数组：{}",sendOpens);
        for(List<String> tempOpen : sendOpens){
            MessageEntity messageEntity = new MessageEntity();
            //构建发送消息体
            messageEntity.setOpen_ids(tempOpen);
            messageEntity.setMsg_type("post");
            String sendContent = "{\"post\":{\"zh_cn\":{\"title\":\"工时填报提醒\",\"content\":[[{\"tag\":\"text\",\"text\":\"外网地址 :\"},{\"tag\":\"a\",\"href\":\"http://114.242.175.67:8085/webpage/work-time-board/out\",\"text\":\"立即填报\"}],[{\"tag\":\"text\",\"text\":\"公司内网 :\"},{\"tag\":\"a\",\"href\":\"http://172.52.0.3:8085/webpage/work-time-board\",\"text\":\"立即填报\"}]]}}}";
            messageEntity.setContent(JSONObject.parseObject(sendContent));
            log.info("等待发送用户队列：{}",JSONObject.toJSONString(messageEntity));
            sendMessage.sendMessageBatch(messageEntity);
        }

    }

    public void sendNotMakeMessage(){
        log.info("进入发送消息方法：给审批人发送");
        List<Work> works = workMapper.selectList(new QueryWrapper<Work>().select("make_user_id").isNull("make_status"));
        List<Integer> collect = works.stream().map(Work::getMakeUserId).collect(Collectors.toList());
        List<Integer> collect1 = collect.stream().distinct().collect(Collectors.toList());
        log.info("未审批的{}",collect1);
        DataSourceContextHolder.setContextHolder("db2");
        List<UserInfo> userInfos = userInfoMapper.selectList(new QueryWrapper<UserInfo>().select("phone").in("id", collect1));
        DataSourceContextHolder.clear();
        List<String> userTels = userInfos.stream().map(UserInfo::getPhone).collect(Collectors.toList());
        //将查询到的用户手机号按照没个list50个手机号进行分割查询用户openid（因为飞书根据手机号查询用户的参数限制未最大50个）
        List<List<String>> lists = ListUtil.cutApart(50, userTels.stream().distinct().collect(Collectors.toList()));
        List<String> allReadSendUserList = new ArrayList<>();
        //循环根据手机号查询用户openid列表
        for(List<String> tels : lists){
            List<String> userInfoList = feiShuUtil.getUserInfoList(tels);
            allReadSendUserList.addAll(userInfoList);
        }
        List<List<String>> sendOpens = ListUtil.cutApart(200, allReadSendUserList);
        log.info("list:{}",JSONObject.toJSONString(sendOpens));
        for(List<String> tempOpn : sendOpens){
            MessageEntity messageEntity = new MessageEntity();
            //构建发送消息体
            messageEntity.setOpen_ids(tempOpn);
            messageEntity.setMsg_type("post");
            String sendContent = "{\"post\":{\"zh_cn\":{\"title\":\"工时审批提醒\",\"content\":[[{\"tag\":\"text\",\"text\":\"有未审批的工时等待您的审批:\"},{\"tag\":\"a\",\"text\":\"内网地址 |  \",\"href\":\"http://172.52.0.3:8085/webpage/work-time-board\"},{\"tag\":\"a\",\"text\":\"外网地址\",\"href\":\"http://114.242.175.67:8085/webpage/work-time-board/out\"}]]}}}";
            messageEntity.setContent(JSONObject.parseObject(sendContent));
            log.info("等待发送用户队列：{}",JSONObject.toJSONString(messageEntity));
            sendMessage.sendMessageBatch(messageEntity);
            log.info("未审批提醒：{}",collect1);
        }
    }

    /*-------------------------------------------------OA同步相关--------------------------------------------------*/

    @Scheduled(cron = "0 0 1 * * ?")    //每日凌晨1点执行导入用户
    public void importOaUser(){
        long start = System.currentTimeMillis();
        log.info("------------------------------start import oa system new user------------------------");
        log.info("开始同步OA系统人员信息");
        oaService.importOaUser();
        log.info("OA人员信息查询成功，开始更新部门信息");
        oaService.importOaDept();
        log.info("部门信息更新成功，开始注册新加入的用户");
        oaService.registerBatch("http://172.52.0.3:8085/UserSystem/user/register"); //后期改成动态管理
        log.info("用户注册完成，开始更新权限系统中人员部门信息");
        oaService.refreshUserDept();
        long end = System.currentTimeMillis();
        log.info("人员信息更新任务完成，共耗时：{} ms",(end-start));
    }
}
